package web.test.zuul;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import web.test.bean.Result;
import web.test.exception.BizException;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

@Component
public class SetErrorResponseFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return Integer.MAX_VALUE;
    }

    @Override
    public boolean shouldFilter() {
        ErrorFilter.ExceptionInfo exceptionInfo = ErrorFilter.hasBizException.get();
        return exceptionInfo != null && exceptionInfo.isError();
    }

    @Override
    public Object run() throws ZuulException {

        ErrorFilter.ExceptionInfo exceptionInfo = ErrorFilter.hasBizException.get();
        BizException bizException = exceptionInfo.getBizException();
        Result result = new Result<>();
        result.setErrorCode(bizException.getCodeMsg().getValue());
        result.setMsg(bizException.getCodeMsg().getErrMsg());
        String body = JSON.toJSONString(result);

        try {
            RequestContext requestContext = RequestContext.getCurrentContext();
            requestContext.getResponse().getOutputStream().write(body.getBytes("utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
